﻿//-----------------------------------------------------------------------
// <copyright file="MercurySystem.cs" company="Craig Longford (deltawolf7@gmail.com)">
//     Copyright (c) Craig Longford. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Delta.Mercury.Business.Web
{
    using System;
    using System.Net;
    using System.Net.Mail;
    using System.Reflection;
    using System.Security.Cryptography;
    using System.Text;
    using Delta.Data.DataExpress;

    /// <summary>
    /// Mercury System class
    /// </summary>
    public static class MercurySystem
    {
        #region Send Mail Method
        /// <summary>
        /// Send email using system configured email server
        /// </summary>
        /// <param name="to">Array of address to send to</param>
        /// <param name="subject">Subject of the email</param>
        /// <param name="message">Body of the email</param>
        public static void SendEmail(string[] to, string subject, string message)
        {
            if (!String.IsNullOrEmpty(Settings.GetMailServer()))
            {
                SmtpClient client = new SmtpClient(Settings.GetMailServer(), Settings.GetMailServerPort());
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(Settings.GetMailServerUsername(), Settings.GetMailServerPassword());
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress(Settings.GetMailServerSendAs());

                foreach (string email in to)
                {
                    mailMessage.To.Add(new MailAddress(email));
                }

                mailMessage.IsBodyHtml = true;
                mailMessage.Headers.Add("X-Sender", "Mercury Business Framework, Version " + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                mailMessage.Headers.Add("X-Author", "Written by Craig Longford (deltawolf7@gmail.com)");
                mailMessage.Headers.Add("X-URL", "http://www.deltasblog.co.uk");
                mailMessage.Subject = subject;
                mailMessage.Body = message;

                try
                {
                    client.SendAsync(mailMessage, null);
                }
                catch (SmtpException ex)
                {
                    EventLogMessage.CreateEventLog("Mercury Email System", ex.Message, EventLogType.Error);
                }
            }
            else
            {
                EventLogMessage.CreateEventLog("Mercury Email System", "Mail server has not been defined, email was not send.", EventLogType.Error);
            }
        }
        #endregion
    }
}
